/*
 * TCSS 445 - Major Project
 * 
 * Author: Chris Davidson
 * Author: Dallas Rosson
 */
package view;

import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.*;
import controller.SQLConnectionMaker;
import java.sql.ResultSet;
import model.Patron;
import model.Book;

/**
 * MainFrame
 * 
 * The main graphic user interface for use with NewportProjectDriver.
 *
 * @author Dallas Rosson
 * @author Chris Davidson
 * @version 1.0, 23 May 2012
 */
public class MainFrame extends JFrame {
    
    /**
     * The main panel.
     */
    private final JPanel my_mainPanel = new JPanel();
    
    /**
     * The menu bar.
     */
    private final JMenuBar my_menuBar = new JMenuBar();
    
    /**
     * The file menu.
     */
    private final JMenu my_fileMenu = new JMenu("File");
    
    /**
     * The run menu.
     */
    private final JMenu my_runMenu = new JMenu("Run");
    
    /**
     * The help menu.
     */
    private final JMenu my_helpMenu = new JMenu("Help");
       
    /**
     * The clear system output item in file menu.
     */
    private final JMenuItem my_clearOutputMenuItem = new JMenuItem("Clear Output Display");
    
    /**
     * The exit menu item in file menu..
     */
    private final JMenuItem my_exitMenuItem = new JMenuItem("Exit");
    
    /**
     * The run search menu item in run menu.
     */
    private final JMenuItem my_runSearchMenuItem = new JMenuItem("Run Action Item");
        
    /**
     * The read me menu item in help menu.
     */
    private final JMenuItem my_readMenuItem = new JMenuItem("Read Me...");
    
    /**
     * The about menu item in help menu.
     */
    private final JMenuItem my_aboutMenuItem = new JMenuItem("About...");
    
    /**
     * The center panel.
     */
    private final JPanel my_centerPanel = new JPanel();
    
    /**
     * The output text area.
     */
    private final JTextArea my_outputTextArea = new JTextArea();
    
    /**
     * The radio button panel.
     */
    private final JPanel my_radioBtnPanel = new JPanel();
    
    /**
     * The user input text area.
     */
    private final JTextField my_userInputTextField = new JTextField();
    
    /**
     * The database connection.
     */
    private final Connection my_connection;
    
    /**
     * A generic statement object to send statements to the sql database.
     */
    private final Statement my_statement;
    
    /**
     * The query string.
     */
    private String my_queryString = "";
    
    /**
     * The query case number.
     */
    private int my_queryNumber = 0;
    
    /**
     * The input string.
     */
    private String my_inputString = "";
    
    /**
     * The result set.
     */
    private ResultSet my_resultSet;
    
    /**
     * The patron.
     */
    private Patron my_patron = new Patron();
    
    /**
     * The book.
     */
    private Book my_book = new Book();
    
    
    /**
     * The constructor for MainFrame. 
     */
    public MainFrame() throws Exception {
                
        my_connection = SQLConnectionMaker.getConnection();     
        my_statement = my_connection.createStatement();
        
    }
    
    // GUI Initializer
    
    /**
     * Initializes the GUI.
     */
    public void initialize() throws Exception {
        
        this.setPreferredSize(new Dimension(600, 500));
        this.setResizable(false);
        this.setVisible(true);
        this.setTitle("Newport Oldtown Library Catalog");
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
               
        my_mainPanel.setVisible(true);
        my_mainPanel.setLayout(new BorderLayout());
        
        my_centerPanel.setLayout(new FlowLayout());        
        my_centerPanel.setVisible(true);
        
        my_outputTextArea.setEditable(false);     
        
        my_outputTextArea.setPreferredSize(new Dimension(575, 225));
        my_outputTextArea.setBorder(BorderFactory.createLineBorder(Color.black));
        
        JLabel infoLbl = new JLabel("Input:");
        
        my_userInputTextField.setVisible(true);
        my_userInputTextField.setPreferredSize(new Dimension(540, 25));
        my_userInputTextField.setBorder(BorderFactory.createLineBorder(Color.black));
        
        initializeSearchButtons();
        my_centerPanel.add(infoLbl);
        my_centerPanel.add(my_userInputTextField);
        my_centerPanel.add(my_outputTextArea);
        
        initializeMenu();
        my_mainPanel.add(BorderLayout.CENTER, my_centerPanel);
        initializeButtons();
        
        this.add(my_mainPanel);
        
        pack();
    }
    
    // Helpers
    
    /**
     * Initialize menu.
     */
    private void initializeMenu() {
                
        my_aboutMenuItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent the_e) {
                
                JOptionPane.showMessageDialog(my_mainPanel, 
                        "A database access tool created for the Newport Library.\n\n" +
                        "Author: Chris Davidson\n" +
                        "Author: Dallas Rosson\n" +
                        "Version: 1.0", 
                        "About", JOptionPane.INFORMATION_MESSAGE);
            }
        });
        
        my_readMenuItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent the_e) {
                
                JFrame readMeFrame = new JFrame();
                JTextArea readMeTextArea = new JTextArea();
                
                readMeFrame.setTitle("Read Me");
                readMeFrame.setLayout(new BorderLayout());
                readMeFrame.setPreferredSize(new Dimension(500, 500));
                readMeFrame.setResizable(true);
                
                JScrollPane scrollPane = new JScrollPane(readMeTextArea);
                scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
                
                readMeFrame.add(BorderLayout.CENTER, scrollPane);
                
                readMeTextArea.append(createReadMeText());
                
                readMeFrame.pack();
                readMeFrame.setVisible(true);
                
                
            }
        });       
        
        my_exitMenuItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent the_e) {
                
                System.exit(0);                
            }
        });
        
        my_clearOutputMenuItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent the_e) {
                
                my_outputTextArea.setText("");
            }
        });
        
        // Add components to the menu bar.
        
        my_fileMenu.add(my_clearOutputMenuItem);
        my_fileMenu.add(my_exitMenuItem);
        
        my_runMenu.add(my_runSearchMenuItem);
        
        my_helpMenu.add(my_readMenuItem);
        my_helpMenu.add(my_aboutMenuItem);
        
        my_menuBar.add(my_fileMenu);
        my_menuBar.add(my_runMenu);
        my_menuBar.add(my_helpMenu);
        
        my_menuBar.setVisible(true);
        
        my_mainPanel.add(BorderLayout.NORTH, my_menuBar);
    }  
    
    /**
     * Initializes the program buttons.
     */
    private void initializeButtons() {
        
        JButton runSearchBtn = new JButton("Run Action Item");
        JButton clearOutputBtn = new JButton("Clear Output");
        JButton exitBtn = new JButton("Exit");
        
        runSearchBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent the_e) {
                
                int updateQuery = 0;
                
                switch(my_queryNumber) {
                    
                    case 0: my_outputTextArea.append("Patron added.../n");
                                    
                            try { // Attempts to execute the update.
                                
                                my_patron = new Patron();
                                PatronDataInputFrame dif = new PatronDataInputFrame(my_patron);
                                dif.initialize();
                                
                                
                                updateQuery = my_statement.executeUpdate(my_queryString);

                            } catch (final SQLException the_ex) {

                                my_outputTextArea.append("ERROR: Query failed to execute!\n");
                            }
                            
                            if (updateQuery != 0 ) {
                                
                                my_outputTextArea.append(my_inputString + " added successfully.\n");
                            }
                            break;
                    
                    case 1: my_outputTextArea.append("Book added.../n");
                            
                            try { // Attempts to execute the update.
                                
                                my_book = new Book();
                                BookDataInputFrame bif = new BookDataInputFrame(my_book);
                                bif.initialize();
                                
                                updateQuery = my_statement.executeUpdate(my_queryString);

                            } catch (final SQLException the_ex) {

                                my_outputTextArea.append("ERROR: Query failed to execute!\n");
                            }
                            
                            if (updateQuery != 0 ) {
                                
                                my_outputTextArea.append(my_inputString + " added successfully.\n");
                            }
                            break;
                    
                    case 2: my_outputTextArea.append("Searched for patron.../n");
                            try { // Attempts to execute the update.
                                
                                my_resultSet = my_statement.executeQuery(my_queryString);

                            } catch (final SQLException the_ex) {

                                my_outputTextArea.append("ERROR: Query failed to execute!\n");
                            }
                            
                            if (updateQuery != 0 ) {
                                
                                try {
                                   my_outputTextArea.append(my_resultSet.getString(0));
                                   
                                } catch (SQLException the_sqle) {                                    
                                    
                                }
                            }
                            break;
                     
                    case 3: my_outputTextArea.append("Searched for book.../n");
                       
                            try { // Attempts to execute the update.
                                
                                my_resultSet = my_statement.executeQuery(my_queryString);

                            } catch (final SQLException the_ex) {

                                my_outputTextArea.append("ERROR: Query failed to execute!\n");
                            }
                            
                            if (updateQuery != 0 ) {
                                
                                try {
                                   my_outputTextArea.append(my_resultSet.getString(0));
                                   
                                } catch (SQLException the_sqle) {                                    
                                    
                                }
                            }
                            break;
                     
                    case 4: my_outputTextArea.append("Reserved book.../n");
                   
                            try { // Attempts to execute the update.
                                
                                updateQuery = my_statement.executeUpdate(my_queryString);

                            } catch (final SQLException the_ex) {

                                my_outputTextArea.append("ERROR: Query failed to execute!\n");
                            }
                            
                            if (updateQuery != 0 ) {
                                
                                my_outputTextArea.append(my_inputString + " reserved.\n");
                            }
                            break;
                    
                    case 5: my_outputTextArea.append("check out book.../n");
                    
                            try { // Attempts to execute the update.
                                
                                updateQuery = my_statement.executeUpdate(my_queryString);

                            } catch (final SQLException the_ex) {

                                my_outputTextArea.append("ERROR: Query failed to execute!\n");
                            }
                            
                            if (updateQuery != 0 ) {
                                
                                my_outputTextArea.append(my_inputString + " checked out.\n");
                            }
                            break;
                     
                    case 6: my_outputTextArea.append("checked in book..../n");
                    
                            try { // Attempts to execute the update.
                                
                                updateQuery = my_statement.executeUpdate(my_queryString);

                            } catch (final SQLException the_ex) {

                                my_outputTextArea.append("ERROR: Query failed to execute!\n");
                            }
                            
                            if (updateQuery != 0 ) {
                                
                                my_outputTextArea.append(my_inputString + " checked in.\n");
                            }
                            break;
                        
                    default: // Do nothing.
                    
                }
            }
        });
        
        exitBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent the_e) {
                
                System.exit(0);
            }
        });
        
        clearOutputBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent the_e) {
                
                my_outputTextArea.setText("");
            }
        });
        
        JPanel btnPanel = new JPanel();
        btnPanel.setLayout(new FlowLayout());
        
        btnPanel.add(runSearchBtn);
        btnPanel.add(clearOutputBtn);
        btnPanel.add(exitBtn);
        
        my_mainPanel.add(BorderLayout.SOUTH, btnPanel);
        
    }
    
    /**
     * Creates the radio buttons for search select.
     */
    private void initializeSearchButtons() {
        
        JRadioButton addPatronRadioBtn = new JRadioButton();
        JRadioButton addBookRadioBtn = new JRadioButton();
        JRadioButton searchPatronRadioBtn = new JRadioButton();
        JRadioButton searchBookRadioBtn = new JRadioButton();
        JRadioButton reserveBookRadioBtn = new JRadioButton();
        JRadioButton checkOutBookRadioBtn = new JRadioButton();
        JRadioButton checkInBookRadioBtn = new JRadioButton();
        
        ButtonGroup radioBtnGroup = new ButtonGroup();
        
        addPatronRadioBtn.setText("Add Patron");
        addBookRadioBtn.setText("Add Book");
        searchPatronRadioBtn.setText("Search for Patron.");
        searchBookRadioBtn.setText("Search for Book");
        reserveBookRadioBtn.setText("Reserve Book");
        checkOutBookRadioBtn.setText("Check Out Book");
        checkInBookRadioBtn.setText("Check In Book");
        
        addPatronRadioBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent the_e) {
                
                my_queryNumber = 0;
                
                my_queryString = ""; // FILL THIS IN!
            }
        });
        
        addBookRadioBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent the_e) {
                
                my_queryNumber = 1;
                my_inputString = retreiveInputText();
                my_queryString = "";
            }
        });
        
        searchPatronRadioBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent the_e) {
                
                my_queryNumber = 2;
                my_inputString = retreiveInputText();
                my_queryString = "";
            }
        });
        
        searchBookRadioBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent the_e) {
                
                my_queryNumber = 3;
                my_inputString = retreiveInputText();
                my_queryString = "";
            }
        });
        
        reserveBookRadioBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent the_e) {
                
                my_queryNumber = 4;
                my_inputString = retreiveInputText();
                my_queryString = "";
            }
        });
        
        checkOutBookRadioBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent the_e) {
                
                my_queryNumber = 5;
                my_inputString = retreiveInputText();
                my_queryString = "";
            }
        });
        
        checkInBookRadioBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent the_e) {
                
                my_queryNumber = 6;
                my_inputString = retreiveInputText();
                my_queryString = "";
            }
        });
        
        radioBtnGroup.add(addPatronRadioBtn);
        radioBtnGroup.add(addBookRadioBtn);
        radioBtnGroup.add(searchPatronRadioBtn);
        radioBtnGroup.add(searchBookRadioBtn);
        radioBtnGroup.add(reserveBookRadioBtn);
        radioBtnGroup.add(checkOutBookRadioBtn);
        radioBtnGroup.add(checkInBookRadioBtn);
        
        my_radioBtnPanel.setLayout(new GridLayout(7, 0));
        my_radioBtnPanel.setPreferredSize(new Dimension(575, 125));
        my_radioBtnPanel.setBorder(BorderFactory.createLineBorder(Color.black));
        
        my_radioBtnPanel.add(addPatronRadioBtn);
        my_radioBtnPanel.add(addBookRadioBtn);
        my_radioBtnPanel.add(searchPatronRadioBtn);
        my_radioBtnPanel.add(searchBookRadioBtn);
        my_radioBtnPanel.add(reserveBookRadioBtn);
        my_radioBtnPanel.add(checkOutBookRadioBtn);
        my_radioBtnPanel.add(checkInBookRadioBtn);
        
        
        my_radioBtnPanel.setVisible(true);
        my_centerPanel.add(my_radioBtnPanel);
        
    }
    
    /**
     * The read me text.
     */
    private String createReadMeText() {
        
        StringBuilder sb = new StringBuilder();
        
        sb.append("Read Me\n\n");
        sb.append("--------------------------------------------\n");
        sb.append(" Running a Search\n");        
        sb.append("--------------------------------------------\n\n");
        sb.append("1. Locate the search you wish to run in the Database Search window\n");
        sb.append("2. Click on the radio button next to the desired search.\n");
        sb.append("3. Click the run button located at the bottom of the program window or\n");
        sb.append(" from the menu bar, click Run and then Run Search.\n\n");
        sb.append("--------------------------------------------\n");
        sb.append(" Clearing Output Window\n");        
        sb.append("--------------------------------------------\n\n");
        sb.append("To clear the output window, click the File option in the menu.\n");
        sb.append("Now click Clear Output Display.  This will clear the output text area.\n"); 
        sb.append("You can also click the Clear Output button at the bottom of the program\n");
        sb.append("with the same results.\n\n");
        sb.append("--------------------------------------------\n");
        sb.append(" Exiting the Program\n");        
        sb.append("--------------------------------------------\n\n");
        sb.append("To exit the program, click either the Exit button at the bottom of\n");
        sb.append("the program menu or click File and then Exit.");
        
        return sb.toString();
    }
    
    /**
     * Gets the input text from the input text box.
     * 
     * @return the input text as a String.
     */
    private String retreiveInputText() {
        
        String tempText = my_userInputTextField.getText();
        
        if (tempText.equals(null)) {
            
            tempText = "";
        }
        
        return tempText;
    }
    
    
}
